//
//  V2LoginViewController.m
//  v2ex-iOS
//
//  Created by Singro on 4/7/14.
//  Copyright (c) 2014 Singro. All rights reserved.
//

#import "JrdLoginViewController.h"
#import "JrdUserModel.h"
#import "JrdAppDelegate.h"
#import "JrdRootViewController.h"
#import "JrdCommon.h"
#import "JrdUserModel.h"
#import "JrdDatamanager.h"
#import "CKHttpCommunicate.h"
#import "PwdForgetViewController.h"
static CGFloat const kContainViewYNormal = 120;
static CGFloat const kContainViewYEditing = 60.0;
#define LOGO_WIDTH      190
#define LOGO_HEIGHT     60
#define LOGO_Y          50
@interface JrdLoginViewController (){
    NSInteger i;
    UIAlertView* alert;
    
}

@property (nonatomic, strong) UIImageView *backgroundImageView;
@property (nonatomic, strong) UIButton    *closeButton;

@property (nonatomic, strong) UIView      *containView;

@property (nonatomic, strong) UIImageView *logoImage;

@property (nonatomic, strong) UILabel     *logoLabel;
@property (nonatomic, strong) UILabel     *descriptionLabel;

@property (nonatomic, strong) UITextField *usernameField;
@property (nonatomic, strong) UITextField *passwordField;
@property (nonatomic, strong) UIButton *forgetpassword;
@property (nonatomic, strong) UIButton    *loginButton;

@property (nonatomic, assign) BOOL isKeyboardShowing;
@property (nonatomic, strong) NSTimer *loginTimer;
@property (nonatomic, assign) BOOL isLogining;
@end

@implementation JrdLoginViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
        self.isKeyboardShowing = NO;
        self.isLogining = NO;
        
    }
    return self;
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)loadView {
    [super loadView];
    
    [self configureViews];
    [self configureContainerView];
    
}


- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    /* iPad有隐藏键盘按钮，没有监听该消息，会导致containView没有恢复 */
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:)
                          name:UIKeyboardWillHideNotification object:nil];
    
    alert = [[UIAlertView alloc] initWithTitle:@"错误" message:@"账号或密码不正确" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

#pragma mark - Layout

- (void)viewWillLayoutSubviews {
    
    self.backgroundImageView.frame = self.view.frame;
    self.closeButton.frame = (CGRect){10, 20, 44, 44};
    
    self.containView.frame = (CGRect){0, kContainViewYNormal, kScreenWidth, 300};
    self.logoLabel.center = (CGPoint){kScreenWidth/2, 30};
    self.descriptionLabel.frame = (CGRect){20, 60, kScreenWidth - 20,70};
    self.usernameField.frame = (CGRect){6, 150, kScreenWidth - 12, 40};
    self.passwordField.frame = (CGRect){6, 200, kScreenWidth - 12, 40};
    self.forgetpassword.frame = (CGRect){6, 240, kScreenWidth - 12, 40};

    self.loginButton.center = (CGPoint){kScreenWidth/2, 300};
    
}

#pragma mark - Configure Views

- (void)configureViews {
    
    self.backgroundImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"bg"]];
    self.backgroundImageView.userInteractionEnabled = YES;
    self.backgroundImageView.contentMode = UIViewContentModeScaleAspectFill;
    [self.view addSubview:self.backgroundImageView];
    
    self.closeButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.closeButton setImage:[UIImage imageNamed:@"close"] forState:UIControlStateNormal];
    [self.closeButton setTintColor:[UIColor whiteColor]];
    self.closeButton.alpha = 0.5;
    if(self.isNeedBack == YES){
        [self.view addSubview:self.closeButton];
    }
    
    self.containView = [[UIView alloc] init];
    [self.view addSubview:self.containView];
    
    self.logoImage = [[UIImageView alloc] initWithFrame:CGRectMake((SCREEN_WIDTH - LOGO_WIDTH)/2, LOGO_Y, LOGO_WIDTH, LOGO_HEIGHT)];
    self.logoImage.image = [UIImage imageNamed:@"logo"];
    [self.containView addSubview:self.logoImage];
    
    //[[UIImage init] imag]
    /*self.logoLabel = [[UILabel alloc] init];
    self.logoLabel.text = @"iMandarin";
    self.logoLabel.font = [UIFont fontWithName:@"Kailasa" size:36];
    self.logoLabel.textColor = kFontColorBlackDark;
    [self.logoLabel sizeToFit];
    //[self.containView addSubview:self.logoLabel];
    
    self.descriptionLabel = [[UILabel alloc] init];
//    self.descriptionLabel.text = @"A community of start-ups, designers, developers and creative people.";
    self.descriptionLabel.text = @"iMandarin，在线教育";
    self.descriptionLabel.font = [UIFont fontWithName:@"Helvetica-Light" size:18];
    self.descriptionLabel.textColor = kFontColorBlackLight;
    self.descriptionLabel.lineBreakMode = NSLineBreakByWordWrapping;
    self.descriptionLabel.numberOfLines = 0;
    self.descriptionLabel.textAlignment = NSTextAlignmentCenter;
    //[self.containView addSubview:self.descriptionLabel];*/
    

    
    // Handles
    @weakify(self);
    [self.closeButton bk_addEventHandler:^(id sender) {
        @strongify(self);
        
        [self dismissViewControllerAnimated:YES completion:nil];
        
    } forControlEvents:UIControlEventTouchUpInside];
    
    [self.containView bk_whenTapped:^{
        @strongify(self);
        [self hideKeyboard];
    }];
    
    [self.backgroundImageView bk_whenTapped:^{
        @strongify(self);
        
        [self hideKeyboard];
        
    }];
    
}

/* 这个方法不止是设置textfield，还有LoginButton，因此这个方法名不合适 */
- (void)configureContainerView {
//- (void)configureTextField {
    
    self.usernameField = [[UITextField alloc] init];
    self.usernameField.textAlignment = NSTextAlignmentCenter;
    self.usernameField.textColor = JRD_RGB(20, 20, 20);//kFontColorBlackDark;
    self.usernameField.font = [UIFont systemFontOfSize:18];
    self.usernameField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"用户名"
       attributes:@{NSForegroundColorAttributeName:[UIColor colorWithWhite:0.836 alpha:1.000],
                   NSFontAttributeName:[UIFont italicSystemFontOfSize:18]}];
    self.usernameField.keyboardType = UIKeyboardTypeEmailAddress;
    self.usernameField.returnKeyType = UIReturnKeyNext;
    self.usernameField.autocapitalizationType = UITextAutocapitalizationTypeNone;
    self.usernameField.autocorrectionType = UITextAutocorrectionTypeNo;
    self.usernameField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    self.usernameField.clearButtonMode = UITextFieldViewModeWhileEditing;
    self.usernameField.rightViewMode = UITextFieldViewModeWhileEditing;
    self.usernameField.backgroundColor = [UIColor clearColor];//JRD_RGB(200, 200, 200);
    self.usernameField.layer.cornerRadius = 20;
    [self.usernameField setBorderStyle:UITextBorderStyleRoundedRect];
    self.usernameField.layer.borderWidth = 1;
    self.usernameField.layer.borderColor = [UIColor whiteColor].CGColor;
    [self.containView addSubview:self.usernameField];

    self.passwordField = [[UITextField alloc] init];
    self.passwordField.textAlignment = NSTextAlignmentCenter;
    self.passwordField.textColor = JRD_RGB(20, 20, 20);//kFontColorBlackDark;
    self.passwordField.font = [UIFont systemFontOfSize:18];
    self.passwordField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"密码"        attributes:@{NSForegroundColorAttributeName:[UIColor colorWithWhite:0.836 alpha:1.000],
                     NSFontAttributeName:[UIFont italicSystemFontOfSize:18]}];
    self.passwordField.secureTextEntry = YES;
    self.passwordField.keyboardType = UIKeyboardTypeASCIICapable;
    self.passwordField.returnKeyType = UIReturnKeyGo;
    self.passwordField.autocapitalizationType = UITextAutocapitalizationTypeNone;
    self.passwordField.autocorrectionType = UITextAutocorrectionTypeNo;
    self.passwordField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    self.passwordField.clearButtonMode = UITextFieldViewModeWhileEditing;
    self.passwordField.rightViewMode = UITextFieldViewModeWhileEditing;
    self.passwordField.backgroundColor= [UIColor clearColor];//JRD_RGB(200, 200, 200);
    self.passwordField.layer.cornerRadius = 20;
    self.passwordField.layer.borderWidth = 1;
    self.passwordField.layer.borderColor = [UIColor grayColor].CGColor;
    [self.containView addSubview:self.passwordField];
    
    self.forgetpassword = [[UIButton alloc] init];
    [self.forgetpassword setTitle:@"Forget?" forState:UIControlStateNormal];
    [self.forgetpassword setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
    [self.forgetpassword setFont:[UIFont systemFontOfSize:18.f]];
    self.forgetpassword.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    self.forgetpassword.backgroundColor = [UIColor clearColor];//JRD_RGB(200, 200, 200);
    
    [self.containView addSubview:self.forgetpassword];
    
    self.loginButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.loginButton setTitle:@"登录" forState:UIControlStateNormal];
    [self.loginButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    [self.loginButton setTitleColor:kFontColorBlackLight forState:UIControlStateHighlighted];
    [self.loginButton setFont:[UIFont boldSystemFontOfSize:22]];
    self.loginButton.size = CGSizeMake((SCREEN_WIDTH - 12), 44);
    //[self.loginButton setBackgroundImage:[V2Helper getImageWithColor:[UIColor colorWithWhite:0.000 alpha:0.30] size:self.loginButton.size] forState:UIControlStateNormal];
    //[self.loginButton setBackgroundImage:[V2Helper getImageWithColor:[UIColor colorWithWhite:0.000 alpha:0.060] size:self.loginButton.size] forState:UIControlStateHighlighted];
    //self.loginButton.layer.borderColor = [UIColor colorWithWhite:0.000 alpha:0.10].CGColor;
    //self.loginButton.backgroundColor = JrdWhite1Color;
    self.loginButton.backgroundColor= [UIColor whiteColor];
    self.loginButton.layer.borderWidth = 1;
    self.loginButton.layer.borderColor = [UIColor whiteColor].CGColor;//[UIColor colorWithRed:0.656 green:0.688 blue:0.869 alpha:1.000].CGColor;
    self.loginButton.layer.cornerRadius = 20;
    [self.containView addSubview:self.loginButton];

    // Handles
    @weakify(self);
    [self.usernameField setBk_shouldBeginEditingBlock:^BOOL(UITextField *textField) {
        @strongify(self);
        //[self.usernameField becomeFirstResponder];
        [self showKeyboard];
        self.usernameField.layer.borderColor = [UIColor whiteColor].CGColor;
        self.passwordField.layer.borderColor = [UIColor grayColor].CGColor;

        return YES;
    }];
    
    [self.usernameField setBk_shouldReturnBlock:^BOOL(UITextField *textField) {
        @strongify(self);
        
        [self.passwordField becomeFirstResponder];
        
        return YES;
    }];
    
    [self.passwordField setBk_shouldBeginEditingBlock:^BOOL(UITextField *textField) {
        @strongify(self);
        //[self.passwordField becomeFirstResponder];

        [self showKeyboard];
        self.usernameField.layer.borderColor = [UIColor grayColor].CGColor;
        self.passwordField.layer.borderColor = [UIColor whiteColor].CGColor;

        return YES;
    }];
    
    [self.passwordField setBk_shouldReturnBlock:^BOOL(UITextField *textField) {
        @strongify(self);
        
        [self login_test1];
        return YES;
    }];
    
    [self.loginButton bk_addEventHandler:^(id sender) {
        @strongify(self);
        
        [self login_test1];
    } forControlEvents:UIControlEventTouchUpInside];
    [self.forgetpassword bk_addEventHandler:^(id sender) {
        @strongify(self);
        
        [self forgetPassword];
    } forControlEvents:UIControlEventTouchUpInside];

}

- (void)forgetPassword{
    PwdForgetViewController* forgetView = [[PwdForgetViewController alloc] init];
    
    [self presentViewController:forgetView animated:YES completion:^{
        
    }];

}
#pragma mark - Private Methods

- (void)beginLogin {
    
    self.isLogining = YES;
    
    self.usernameField.enabled = NO;
    self.passwordField.enabled = NO;
    
    static NSUInteger dotCount = 0;
    dotCount = 1;
    [self.loginButton setTitle:@"登录." forState:UIControlStateNormal];

    @weakify(self);
    self.loginTimer = [NSTimer bk_scheduledTimerWithTimeInterval:0.5 block:^(NSTimer *timer) {
        @strongify(self);
        
        if (dotCount > 3) {
            dotCount = 0;
        }
        NSString *loginString = @"登录";
        for (int i = 0; i < dotCount; i ++) {
            loginString = [loginString stringByAppendingString:@"."];
        }
        dotCount ++;
        
        [self.loginButton setTitle:loginString forState:UIControlStateNormal];
        
    } repeats:YES];
    
}

- (void)endLogin {
    
    self.usernameField.enabled = YES;
    self.passwordField.enabled = YES;
    
    [self.loginButton setTitle:@"登录" forState:UIControlStateNormal];

    self.isLogining = NO;
    
    [self.loginTimer invalidate];
    self.loginTimer = nil;
    
}

- (void)GoInApp{
    
    [self hideKeyboard];
    [UIView animateWithDuration:1 animations:^{
        
        /* 改变透明度, 并重新指定跟视图 */
        self.view.alpha = 0.1;
    } completion:^(BOOL finished) {
        /* 重新指定跟视图 */
        if(self.isNeedBack  == TRUE){
            JrdAppDelegate *tempAppDelegate = [UIApplication sharedApplication].delegate;
            JrdRootViewController* rootView = [[JrdRootViewController alloc] init];
            tempAppDelegate.window.rootViewController = rootView;
        }else{
            JrdRootViewController* rootView = [[JrdRootViewController alloc] init];
            
            [self presentViewController:rootView animated:YES completion:^{
                
            }];

        }
    }];
    
    [[NSUserDefaults standardUserDefaults]setBool:YES forKey:@"isLogin"];
}

- (void)loadImageAndSave:(id)result{
    NSData* image_data = (NSData*)result;
    UIImage* image = [UIImage imageWithData:image_data];
    
    NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentPath = [path objectAtIndex:0];
    
    NSString *imageDocPath = [documentPath stringByAppendingPathComponent:@"ImageFile"];
    //创建ImageFile文件夹
    [[NSFileManager defaultManager] createDirectoryAtPath:imageDocPath withIntermediateDirectories:YES attributes:nil error:nil];
    
    NSString* imagePath = [imageDocPath stringByAppendingPathComponent:@"image.png"];
    NSData *data;
    
    if (UIImagePNGRepresentation(image)) {
        //返回为png图像。
        data = UIImagePNGRepresentation(image);
    }else {
        //返回为JPEG图像。
        data = UIImageJPEGRepresentation(image, 1.0);
    }
    [[NSFileManager defaultManager] createFileAtPath:imagePath contents:data attributes:nil];

}

- (void)login_test1{
    if(nil == self.usernameField.text || 0 == self.usernameField.text.length
       || nil == self.passwordField.text || 0 == self.passwordField.text.length){
        
        [alert show];
        [self endLogin];
    
        return;
    }
    NSDictionary *parameter = @{
                                @"username":self.usernameField.text,
                                @"password":self.passwordField.text
                                };
    /*JrdUserModel* user1 = [[JrdUserModel alloc] init];
    user1.userId = @(4);
    [JrdDatamanager manager].user = user1;
    [self GoInApp];
     return;*/

    [CKHttpCommunicate createRequest:HTTP_IMANDARIN_LOGIN WithParam:parameter withMethod:GET success:^(id result) {
        if (result) {
            NSLog(@"result:%@",result);
            JrdUserModel* user = [[JrdUserModel alloc] init];
            user.isLogin =  YES;
            user.userId =  [result valueForKey:@"id"];
            user.userName = self.usernameField.text;//@"wuzhaolin";
            user.password = self.passwordField.text;
            [JrdDatamanager manager].user = user;
            [self.passwordField resignFirstResponder];
            user.isLogin =  YES;
            NSDictionary *parameter_ = @{
                                        @"userid":[result valueForKey:@"id"]
                                        };
            [CKHttpCommunicate createRequest:HTTP_GET_USER_INFO WithParam:parameter_ withMethod:GET success:^(id result) {
                if(result){
                    [JrdDatamanager manager].user.userEamil = [result[0] valueForKey:@"email"];
                    [JrdDatamanager manager].user.phoneNumber = [result[0] valueForKey:@"phone"];

                    [[JrdDatamanager manager] setUserEmail:[result[0] valueForKey:@"email"]];
                    [[JrdDatamanager manager] setUserPhone:[result[0] valueForKey:@"phone"]];
                    [self.passwordField resignFirstResponder];
                    [self endLogin];
                    [self GoInApp];
                }
            }failure:^(NSError *erro) {
                [alert show];
                
                [self endLogin];
            } showHUD:self.view];
            
            NSDictionary *parameter_1 = @{@"userid":[JrdDatamanager manager].user.userId};
            
            [CKHttpCommunicate createRequest:HTTP_GET_IMAGE WithParam:parameter_1 withMethod:GET success:^(id result) {
                if(result){
                    [self loadImageAndSave:result];
                }
            }failure:^(NSError *erro) {
                NSLog(@"zlwu add ");
            } showHUD:self.view];
            
        }
    } failure:^(NSError *erro) {
        [alert show];

        [self endLogin];
    } showHUD:self.view];

}

- (void)showKeyboard {
    
    if (self.isKeyboardShowing) {
        ;
    } else {
        [UIView animateWithDuration:0.3 animations:^{
            self.containView.y      = kContainViewYEditing;
            self.descriptionLabel.y -= 5;
            self.usernameField.y    -= 20;
            self.passwordField.y    -= 22;
            self.forgetpassword.y -= 23;
            self.loginButton.y      -= 24;
        }];
        self.isKeyboardShowing = YES;
    }
    
}

- (void)hideKeyboard {
    
    if (self.isKeyboardShowing) {
        self.isKeyboardShowing = NO;
        [[UIApplication sharedApplication].keyWindow endEditing:YES];
        [UIView animateWithDuration:0.3 animations:^{
            self.containView.y      = kContainViewYNormal;
            self.descriptionLabel.y += 5;
            self.usernameField.y    += 20;
            self.passwordField.y    += 22;
            self.forgetpassword.y   += 23;
            self.loginButton.y      += 24;
        } completion:^(BOOL finished) {
        }];
    }

}

- (BOOL)isValidEmail:(NSString *)email{
    if (email == nil) {
        return NO;
    }
    NSString *phoneRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex];
    return [phoneTest evaluateWithObject:email];
}

#pragma mark - Keyboard Notification
- (void)keyboardWillHide:(NSNotification *)notification {
    [self hideKeyboard];
}

@end
